class Document < ActiveRecord::Base

  hobo_model
  
  acts_as_ferret :fields => [:identifier, :title, :keywords, :dated]
  
  acts_as_reportable
  
  belongs_to  :person, :foreign_key => :person_id 
  belongs_to  :company, :foreign_key => :company_id 
  belongs_to  :department, :foreign_key => :department_id
  belongs_to  :user, :foreign_key => :user_id 
  
  set_search_columns :title, :identifier, :keywords
  
  set_creator_attr :user
  before_save :eval_identifier
  
  def self.most_recent
    find(:all, :limit => 3, :order => 'updated_at DESC')
  end
  
  def self.full_text_search(q, options = {})
    return nil if q.nil? or q==""
    default_options = {:limit => 10, :page => 1}
    options = default_options.merge options
   
    # get the offset based on what page we're on
    options[:offset] = options[:limit] * (options.delete(:page).to_i-1)  
   
    # now do the query with our options
    results = self.find_by_contents(q, options)
    return [results.total_hits, results]
  end

  # --- Hobo Permissions --- #

  def creatable_by?(creator)
    creator == user and not creator.guest?
  end

  def updatable_by?(updater, new)
    updater == user and same_fields?(new, :user)
  end

  def deletable_by?(deleter)
    deleter == user 
  end

  def viewable_by?(viewer, field)
    true
  end
  
  private
  
  def eval_identifier
    
    dept_no = department.id  rescue dept_no = 0
    
    # find all documents in current document's department 
    all_docs = department.documents.find(:all) rescue all_docs = nil
    
    unless all_docs.nil?
      all_doc_ids = []
      all_docs.each{|doc| all_doc_ids << doc.id }
      
      # if the doc id is nil it must be a new doc and its id will be the next in the sequence 
      new_doc_id = id.nil? ? (Document.count+1) : id
      
      # add the current document's id to the all indices, unless its already there 
      all_doc_ids << new_doc_id unless not all_doc_ids.index(id).nil? 
      
      all_doc_ids.sort! 
      
      # set the document number part of the identifier to number i, 
      # where i is the i-th document in the department. If the 
      doc_no = (all_doc_ids.index(new_doc_id)+1) rescue doc_no = 0 
    else
      doc_no = 0
    end
    
    self.identifier =  "%02d" % (dept_no.to_s) + "-" + "%03d" % (doc_no.to_s)
  end
  
end
